﻿CREATE PROCEDURE [dbo].[AbsenceLinesInsert]
(--Отказ покупателю в случае отсутствия товара в продаже
	@DocId int,
	@GoodsId int,
	@Qntty int,		
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int
DECLARE @intDocTypeId int, @intNextId int

SET NOCOUNT ON
IF (@DocId Is Null) OR (@GoodsId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@Qntty <= 0)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Количество д.б. больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

SELECT @intDocTypeId = DocTypeId
FROM [CA].[Documents] WHERE Id = @DocId
IF (@intDocTypeId Is Null)
BEGIN
	SELECT @intErrCode = 3, @strMsg = 'Не найден документ с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (@intDocTypeId <> 14)
BEGIN
	SELECT @intErrCode = 4, @strMsg = 'Неправильный тип документа с идентификатором ' + cast(@DocId as varchar(20)) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Common', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;

INSERT INTO CD.ManageDocLines
(Id, [DocId], [GoodsId], Qntty,  
[Note], [MD], [MW]) 
VALUES (@intNextId, @DocId, @GoodsId, @Qntty,
@Note, @MD, @MW);

SELECT Id, DepartmentId, [DocId], [GoodsId], Qntty,  
[Note], [MD], [MW]
FROM CD.ManageDocLines WHERE Id = @intNextId

RETURN 0